package com.lsa.letcode.the2.add2num;

import com.lsa.letcode.common.ListNode;

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
        	return l2;
        }
        else if (l2 == null) {
        	return l1;
        }
        
        ListNode first = new ListNode(0);
        ListNode cur = first;
        
        int carry = 0;
        boolean isBreak = false;
        do{
        	int sum = (l1 != null? l1.val : 0) + (l2 != null? l2.val : 0) + carry;
        	carry = sum / 10;
        	cur.val = sum % 10;
        	
        	l1 = l1 != null? l1.next : null;
        	l2 = l2 != null? l2.next : null;
        	
        	boolean isAllocate = false;
        	if (l1 != null || l2 != null) {
        		isAllocate = true;
        	}
        	else {
        		if (carry != 0) {
        			isAllocate = true;
        		}
        		isBreak = true;
        	}
        	if (isAllocate) {
        		cur.next = new ListNode(0);
        		cur = cur.next;
        	}
        }
        while(!isBreak);
        
        if (carry != 0) {
        	cur.val = carry;
        }
        
        return first;
    }
}